package net.mujiwulian.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import net.mujiwulian.entity.Day;
import net.mujiwulian.entity.DayAcupoint;
import net.mujiwulian.entity.Disease;
import net.mujiwulian.entity.DiseaseType;
import net.mujiwulian.service.*;
import net.mujiwulian.view.DayDetails;
import net.mujiwulian.view.DiseaseDetails;
import net.mujiwulian.view.UserSimple;
import net.mujiwulian.vo.PageQuery;
import net.mujiwulian.vo.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: silence
 * @Description:
 * @Date:Create：in 2019/12/30 14:45
 */
@Slf4j
@RestController
@RequestMapping("/disease")
public class DiseaseController {

    private final DiseaseService diseaseService;
    private final DiseaseDetailsService diseaseDetailsService;
    private final DiseaseTypeService diseaseTypeService;
    private final DayService dayService;
    private final DayDetailsService dayDetailsService;
    private final DayAcupointService dayAcupointService;

    public DiseaseController(DiseaseService diseaseService, DiseaseDetailsService diseaseDetailsService, DiseaseTypeService diseaseTypeService, DayService dayService, DayDetailsService dayDetailsService, DayAcupointService dayAcupointService) {
        this.diseaseService = diseaseService;
        this.diseaseDetailsService = diseaseDetailsService;
        this.diseaseTypeService = diseaseTypeService;
        this.dayService = dayService;
        this.dayDetailsService = dayDetailsService;
        this.dayAcupointService = dayAcupointService;
    }

    /**
     * ----------------------------------------------病例分类---------------------------------------------------
     */

    @GetMapping("/type/select")
    public Result<List<DiseaseType>> selectType(boolean b) {
        LambdaQueryWrapper<DiseaseType> lq = Wrappers.lambdaQuery();
        if (b) {
            lq.select(DiseaseType::getId, DiseaseType::getName);
        }
        return new Result<>(Result.CodeStatus.OK, "获取商品分类信息", diseaseTypeService.list(lq));
    }

    @PostMapping("/type/delete")
    @Transactional(rollbackFor = {Exception.class})
    public Result<Void> deleteType(@RequestBody DiseaseType diseaseType) {
        return new Result<>("删除病例分类", diseaseTypeService.removeById(diseaseType.getId()));
    }

    @PostMapping("/type/insertOrUpdate")
    public Result<Void> insertOrUpdateType(UserSimple userSimple, @RequestBody DiseaseType diseaseType) {
        if (diseaseType.getId() == null && diseaseTypeService.getOne(new QueryWrapper<DiseaseType>().eq("name", diseaseType.getName())) != null) {
            return new Result<>(Result.CodeStatus.FAIL, "名字已存在");
        }
        diseaseType.setUpdateTime(LocalDateTime.now());
        diseaseType.setOperator(userSimple.getUsername());
        return new Result<>("操作", diseaseTypeService.saveOrUpdate(diseaseType));
    }


    /**
     * ----------------------------------------------病例列表---------------------------------------------------
     */
    @PostMapping("/select")
    public Result<IPage<DiseaseDetails>> select(@RequestBody PageQuery<DiseaseDetails> pageQuery) {
        DiseaseDetails diseaseDetails = pageQuery.getT() == null ? new DiseaseDetails() : pageQuery.getT();
        LambdaQueryWrapper<DiseaseDetails> lq = Wrappers.lambdaQuery();
        lq.like(StringUtils.isNotEmpty(diseaseDetails.getTypeName()), DiseaseDetails::getTypeName, diseaseDetails.getTypeName());
        lq.like(StringUtils.isNotEmpty(diseaseDetails.getName()), DiseaseDetails::getName, diseaseDetails.getName());
        return new Result<>(Result.CodeStatus.OK, "获取病例信息", diseaseDetailsService.page(pageQuery.getPageCondition(), lq));
    }

    @GetMapping("/details")
    public Result<List<DayDetails>> details(Integer id) {
        return new Result<>(Result.CodeStatus.OK, "获取详情", dayDetailsService.list(new QueryWrapper<DayDetails>().eq("disease_id", id)));
    }

    @PostMapping("/insertOrUpdate")
    @Transactional(rollbackFor = {Exception.class})
    public Result<Void> insertOrUpdate(@RequestBody Disease disease) {
        if (disease.getId() == null) {
            if (!diseaseService.list(new QueryWrapper<Disease>().eq("name", disease.getName())).isEmpty()) {
                return new Result<>(Result.CodeStatus.FAIL, "名字已存在");
            }
            disease.setCreateTime(LocalDateTime.now());
        }
        diseaseService.saveOrUpdate(disease);
        List<Day> days = disease.getDays();
        //天
        if (disease.getId() != null && days != null && !days.isEmpty()) {
            List<Integer> dayIds = dayService.list(new QueryWrapper<Day>().select("id").eq("disease_id", disease.getId())).stream().map(Day::getId).collect(Collectors.toList());
            dayIds = dayIds.stream().filter(id -> !days.stream().map(Day::getId).collect(Collectors.toList()).contains(id)).collect(Collectors.toList());
            if (!dayIds.isEmpty()) {
                dayService.removeByIds(dayIds);
            }
        }
        if (days != null && !days.isEmpty()) {
            days.forEach(day -> day.setDiseaseId(disease.getId()));
            dayService.saveOrUpdateBatch(days);
            //穴位
            days.forEach(day -> {
                List<DayAcupoint> dayAcupoints = day.getDayAcupoints();
                dayAcupoints.forEach(dayAcupoint -> dayAcupoint.setDayId(day.getId()));
                if (day.getId() != null) {
                    List<Integer> dayAcupointIds = dayAcupointService.list(new QueryWrapper<DayAcupoint>().eq("day_id", day.getId())).stream().map(DayAcupoint::getId).collect(Collectors.toList());
                    dayAcupointIds = dayAcupointIds.stream().filter(id -> !dayAcupoints.stream().map(DayAcupoint::getId).collect(Collectors.toList()).contains(id)).collect(Collectors.toList());
                    if (!dayAcupointIds.isEmpty()) {
                        dayAcupointService.removeByIds(dayAcupointIds);
                    }
                }
                dayAcupointService.saveOrUpdateBatch(dayAcupoints);
            });
        }
        return new Result<>("操作", true);
    }

    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody List<Integer> ids) {
        return new Result<>("删除病例", diseaseService.removeByIds(ids));
    }

}
